//
//  YYEStatusListViewModel.swift
//  weibo14
//
//  Created by mac on 16/3/7.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SDWebImage


class YYEStatusListViewModel: NSObject {

    // 当前视图模型对应的模型,供首页使用的微博数组
    var statusArray: [YYEStatusViewModel]?
    
    
    // 专门用于加载数据的方法
    func loadData(isPullUp: Bool, finished: (isSuccess: Bool, count: Int)->()){
    
        var maxID:Int64 = 0
        var sinceId: Int64 = 0
        if isPullUp { //是请求数据
        
            maxID = statusArray?.last?.status?.id ?? 0
            
            if maxID != 0 {
            
                maxID--
            }
        } else {
            sinceId = statusArray?.first?.status?.id ?? 0
            
        }

        
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        // 参数
        let parameters = [
            "access_token": YYEUserAccountViewModel.sharedAccountViewModel.accessToken!,
            "max_id": "\(maxID)",
            "since_id": "\(sinceId)"

        ]
        
        YYENetworkTools.sharedTools.requst( urlString: url, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
            
                print(error)
               // finished(isSuccess: false, count:0)
                finished(isSuccess: false, count: 0)

                
                return
            }
            

            
            // 取到微博字典的数据进行遍历字典转模型
            let dicts = responseObject!["statuses"] as! [[String: AnyObject]]
            
            // 初始化一个临时数组
            var tempArray = [YYEStatusViewModel]()
            for dict in dicts {
                // 字典转模型
                let status = YYEStatus(dict: dict)
                
                let viewModel = YYEStatusViewModel(status: status)
                
                tempArray.append(viewModel)
            }
            
            // 赋值
            // self.statusArray = tempArray
            if self.statusArray == nil {
                self.statusArray = [YYEStatusViewModel]()
            }

            if isPullUp {
                self.statusArray! = self.statusArray! + tempArray
            } else {
            
                self.statusArray! = tempArray + self.statusArray!
            }
            

            
            
            
            // finished(isSuccess: true)
          
            self.cacheSingleImage(tempArray, finished: finished)
            
        }
    }
    
    private func cacheSingleImage(viewModels: [YYEStatusViewModel],finished: (isSuccess: Bool,count:Int)->()){
        
        // 调度组
        let group = dispatch_group_create()
        let queue = dispatch_get_main_queue()
        // 2. 循环调用下载图片的方法

        
        // 遍历模型
        for viewModel in viewModels {
       
            // 如果原创的有就不显示转发的
            var urlStr = viewModel.status?.pic_urls
            
  
            
            if urlStr == nil || urlStr?.count == 0 {
            
                // 原创没图
                urlStr = viewModel.status?.retweeted_status?.pic_urls
                
                // 设置转发微博的------------
                // 原创有图 判断是否是一张
                if urlStr?.count == 1 {
                    // 确实是一张
                    guard let urlString = urlStr?.first?.thumbnail_pic else {
                        continue
                    }
                    
                    // 做入组操作
                    dispatch_group_enter(group)
                    // 下载图片
                    SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) -> Void in
                        print("下载完成,地址是:\(url.absoluteString)")
                        // 下载完成或者下载失败
                        dispatch_group_leave(group)
                    })
                }
                
                
                
            }else {
            
                //原创有图 判断是否是一张
                if urlStr?.count == 1 {
                    // 确实是一张
                    guard let urlString = urlStr?.first?.thumbnail_pic else {
                        continue
                    }
                    // 做入组操作
                    dispatch_group_enter(group)
                    // 下载图片
                    SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) -> Void in
                        print("下载完成,地址是:\(url.absoluteString)")
                        // 下载完成或者下载失败
                        dispatch_group_leave(group)
                    })
                }
                
                // 原创有图 还要去判断转发
                
                urlStr = viewModel.status?.retweeted_status?.pic_urls
                // 设置转发微博的------------
                // 原创有图 判断是否是一张
                if urlStr?.count == 1 {
                    // 确实是一张
                    guard let urlString = urlStr?.first?.thumbnail_pic else {
                        continue
                    }
                    
                    // 做入组操作
                    dispatch_group_enter(group)
                    // 下载图片
                    SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString), options: [], progress: nil, completed: { (image, error, _, _, url) -> Void in
                        print("下载完成,地址是:\(url.absoluteString)")
                        // 下载完成或者下载失败
                        dispatch_group_leave(group)
                    })
                }
                
            }
            
            
            

            
        }
        
        // 3. 图片下完成之后回调给界面让界面去刷新数据
        dispatch_group_notify(group, queue) { () -> Void in
            print("所有单张图片都下载完成")
            finished(isSuccess: true, count: viewModels.count)
   
        }
        
    }
}
